package com.school.service.impl;

import com.school.entity.User;
import com.school.repository.UserRepository;
import com.school.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    @Override
    public Optional<User> findByStudentId(String studentId) {
        return userRepository.findByStudentId(studentId);
    }

    @Override
    public User save(User user) {
        // 如果是新用户（没有ID），设置创建时间
        if (user.getId() == null) {
            user.setCreateTime(LocalDateTime.now());
        }

        // 更新时间
        user.setUpdateTime(LocalDateTime.now());

        // 如果密码不为空，则加密密码
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }

        return userRepository.save(user);
    }

    @Override
    public boolean checkPassword(User user, String rawPassword) {
        return passwordEncoder.matches(rawPassword, user.getPassword());
    }

    @Override
    public void updatePassword(Long userId, String newPassword) {
        userRepository.findById(userId).ifPresent(user -> {
            user.setPassword(passwordEncoder.encode(newPassword));
            user.setUpdateTime(LocalDateTime.now());
            userRepository.save(user);
        });
    }

    @Override
    public void resetPassword(Long userId) {
        userRepository.findById(userId).ifPresent(user -> {
            // 重置密码为用户名
            user.setPassword(passwordEncoder.encode(user.getUsername()));
            user.setUpdateTime(LocalDateTime.now());
            userRepository.save(user);
        });
    }

    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }

    @Override
    public List<User> findByRole(String role) {
        return userRepository.findByRole(role);
    }

    @Override
    public List<User> findByRoleAndKeyword(String role, String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return userRepository.findByRole(role);
        }
        return userRepository.findByRoleAndKeyword(role, keyword);
    }

    @Override
    public List<User> findByRoleAndClassId(String role, Integer classId) {
        return userRepository.findByRoleAndClassId(role, classId);
    }

    @Override
    public Optional<User> findById(Long id) {
        return userRepository.findById(id);
    }

    @Override
    public void deleteById(Long id) {
        userRepository.deleteById(id);
    }

    @Override
    public void deleteByUsername(String username) {
        userRepository.findByUsername(username).ifPresent(user -> {
            userRepository.delete(user);
        });
    }
}
